import bufferService from "@/service/bufferService"
import requestService from "@/service/requestService"
const userModule = {
    namespaced: true,
    state: {
        userName: bufferService.get(bufferService.USER_NAME),
        //userID: bufferService.get(bufferService.USER_ID)
    },

    mutations: {
        SET_USER_NAME(state, userName) {
            bufferService.set(bufferService.USER_NAME, userName)
            state.userName = userName
        },
        //SET_USER_ID(state, userID) {
        //    bufferService.set(bufferService.USER_ID, userID)
        //    state.userID = userID
        //}
    },

    actions: {
        register(context, { name, telephone, password }) {
            return new Promise((resolve, reject) => {
                var user = {
                    "username": name,
                    "phoneNumber": telephone,
                    "password": password,
                }
                requestService.post('register', user)
                    .then((res) => {
                        context.commit('SET_USER_NAME', res.data.data.username)
                        resolve(res)
                    }).catch((err) => {
                        reject(err)
                    })
            })
        },
        login(context, { name, password }) {
            return new Promise((resolve, reject) => {
                var user = {
                    "username": name,
                    "password": password,
                }
                requestService.post('login', user)
                    .then((res) => {
                        context.commit('SET_USER_NAME', res.data.data.username)
                        resolve(res)
                    }).catch((err) => {
                        reject(err)
                    })
            })
        },
        logout({ commit }) {
            bufferService.set(bufferService.USER_NAME, '')
            commit('SET_USER_NAME', '')
            window.location.reload()
        }
    }
}

export default userModule